package com.efounder.email.adapter;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.email.model.AttachFile;
import com.efounder.email.util.FileUtil;
import com.efounder.http.utils.DownEmailAttachPostUtil;
import com.efounder.http.utils.DownEmailAttachmentUtil;
import com.efounder.ospmobilelib.R;
import com.efounder.utils.ResStringUtil;

import java.util.List;

/**
 * 邮件详情 listview适配器
 *
 * @author yqs
 */
public class DetailListAdapter extends BaseAdapter {

    Context context;
    List<AttachFile> attachFiles;
    DownEmailAttachmentUtil downDPEmail;
    DownEmailAttachPostUtil downEmail;
    ProgressDialog mDialog;
    private String calId;//日程id

    public DetailListAdapter(Context context, List<AttachFile> attachFiles) {
        super();

        this.context = context;
        this.attachFiles = attachFiles;
    }

    //国勘会议管理构造方法
    public DetailListAdapter(Context context, List<AttachFile> attachFiles, String calId) {
        super();

        this.context = context;
        this.attachFiles = attachFiles;
        this.calId = calId;
    }

    // 杀死下载服务
    public void killDownService() {
        if (downDPEmail != null) {
            downDPEmail.taskEnd();
        }
        if (downEmail != null) {
            downEmail.taskEnd();
        }
    }

    @Override
    public int getCount() {

        return attachFiles.size();
    }

    @Override
    public AttachFile getItem(int position) {

        return attachFiles.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @SuppressWarnings("deprecation")
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = View.inflate(context, R.layout.detail_list_items,
                    null);
            new ViewHolder(convertView);
        }
        ViewHolder holder = (ViewHolder) convertView.getTag();
        final AttachFile file = getItem(position);
        String url = file.getAttachPath();
        Bitmap bmp = null;
        if ("DPEMAIL".equals(file.getEmailType())) {
            bmp = FileUtil.getImageFrompath(context, url);
        } else {
            bmp = FileUtil.getImageFrompath(context, file.getAttachName());
        }
        Drawable drawable = new BitmapDrawable(bmp);
        // holder.image.setImageDrawable(file.getAttachImage());
        holder.image.setImageDrawable(drawable);
        holder.fileName.setText(file.getAttachName());
        // 如果附件大小为空 不显示附件大小
        if (file.getAttachSize() == null) {
            holder.fileSize.setVisibility(View.GONE);
        }
        holder.fileSize.setText(file.getAttachSize());
        holder.itemlayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                DownHandler downHandler = new DownHandler();
                try {
                    // 总部和普光的邮件附件下载的方式不一样，普光采用post请求下载
                    // 普光邮箱
                    if ("EMAIL".equals(file.getEmailType())) {
                        downEmail = new DownEmailAttachPostUtil(context, file
                                .getAttachPath(), file, downHandler);
                        downEmail.taskStart();
                    }
                    // 总部邮箱
                    else if ("DPEMAIL".equals(file.getEmailType())) {
                        downDPEmail = new DownEmailAttachmentUtil(context, file
                                .getAttachPath(), file.getAttachName(), downHandler);
                        downDPEmail.taskStart();
                    } else if ("GKEMAIL".equals(file.getEmailType())) {
                        downDPEmail = new DownEmailAttachmentUtil(context, file
                                .getAttachPath(), file.getAttachName(), downHandler);
//                        downDPEmail.taskGKStart(file.getEmailId(), file.getId(),
//                                "https://gkyd.zyof.com.cn/email/downloadAttachment.jspx?emailId=");
                        downDPEmail.taskGKStart(file.getEmailId(), file.getId(),
                                "https://gkyd.zyof.com.cn/mobile/email/downloadAttachment.jspx?emailId=");
                    } else if ("GKMEETING".equals(file.getEmailType())) {//国勘会议
                        downDPEmail = new DownEmailAttachmentUtil(context, file
                                .getAttachPath(), file.getAttachName(), downHandler);
//                        downDPEmail.taskGKStart(calId, file.getId(),
//                                "https://gkyd.zyof.com.cn/calendar/downloadAttachment.jspx?calId=");
                        downDPEmail.taskGKStart(calId, file.getId(),
                                "https://gkyd.zyof.com.cn/mobile/calendar/downloadAttachment.jspx?calId=");
                    } else {
                        downDPEmail = new DownEmailAttachmentUtil(context, file
                                .getAttachPath(), file.getAttachName(), downHandler);
                        downDPEmail.taskStart();
                    }

                } catch (Exception e) {
                    Toast.makeText(context, ResStringUtil.getString(R.string.wechatview_file_not_exist), Toast.LENGTH_SHORT)
                            .show();
                }

            }
        });

        return convertView;
    }

    class ViewHolder {
        /**
         * 附件图片
         */
        public ImageView image;
        /**
         * 附件名称
         */
        public TextView fileName;
        /**
         * 更多按钮
         */
        public ImageView more;
        /**
         * 附件大小
         */
        public TextView fileSize;
        /**
         * listview一个的布局
         */
        public RelativeLayout itemlayout;

        public ViewHolder(View view) {
            image = (ImageView) view.findViewById(R.id.itemfileImage);
            fileName = (TextView) view.findViewById(R.id.itemfilename);
            more = (ImageView) view.findViewById(R.id.detailmore);
            fileSize = (TextView) view.findViewById(R.id.itemfilesize);
            itemlayout = (RelativeLayout) view.findViewById(R.id.itemlayout);
            view.setTag(this);
        }
    }

    public class DownHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    mDialog = new ProgressDialog(context);
                    mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
                    mDialog.setMessage(ResStringUtil.getString(R.string.common_text_please_wait));
                    mDialog.setIndeterminate(false);// 设置进度条是否为不明确
                    mDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
                    mDialog.setCanceledOnTouchOutside(false);
                    mDialog.setOnDismissListener(new OnDismissListener() {

                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            // TODO Auto-generated method stub
                            mDialog = null;
                        }
                    });
                    mDialog.show();

                    break;
                case 1:
                    if (mDialog != null) {
                        mDialog.dismiss();
                        mDialog = null;
                    }
                    break;
                case 2:
                    Toast t2 = Toast.makeText(context, ResStringUtil.getString(R.string.common_text_connect_error), Toast.LENGTH_SHORT);
                    t2.setGravity(Gravity.CENTER, 0, 0);
                    t2.show();
                    break;
                case 3:
//                    Toast t3 = Toast.makeText(context, "已保存到SD卡", Toast.LENGTH_SHORT);
//                    t3.setGravity(Gravity.CENTER, 0, 0);
//                    t3.show();
                    break;
                case 4:
                    Toast t4 = Toast.makeText(context, "请安装该文件类型的程序！", Toast.LENGTH_LONG);
                    t4.setGravity(Gravity.CENTER, 0, 0);
                    t4.show();
                    break;
                case 5:
                    Toast t5 = Toast.makeText(context, "该文件打开失败，请检查手机是否存在打开该文件类型的程序。", Toast.LENGTH_LONG);
                    t5.setGravity(Gravity.CENTER, 0, 0);
                    t5.show();
                    break;

            }
        }
    }
}
